<template>
    <div id="app">
        <el-card shadow="always">
            <el-form :inline="true" size="medium" :model="studentSearch" class="demo-form-inline">
                <el-form-item>
                    <el-input v-model="studentSearch.sname" placeholder="学生姓名" />
                </el-form-item>
                <el-form-item>
                    <el-input v-model="studentSearch.addr" placeholder="学生住址" />
                </el-form-item>
                <el-form-item>
                    <el-select v-model="studentSearch.cid" placeholder="所在班级">
                        <el-option label="所有班级" value="0" />
                        <el-option :label="c.cname" :value="c.cid" v-for="c in classesList" :key="c.cid" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" plain @click="search">查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="success" icon="el-icon-plus" plain @click="addStudent">添加学生</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="danger" icon="el-icon-remove" plain @click="handleDelete">批量删除</el-button>
                </el-form-item>
            </el-form>

            <el-table
                    :data="studentList"
                    style="width: 100%"
                    @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection"></el-table-column>
                <el-table-column label="学号" align="center" prop="sid" width="180" />
                <el-table-column label="姓名" prop="sname" align="center" />
                <el-table-column label="性别" prop="sex" align="center" />
                <el-table-column label="年龄" prop="age" align="center" />
                <el-table-column label="住址" prop="addr" align="center" />
                <el-table-column label="所在班级" prop="cname" align="center" />
                <el-table-column label="操作" align="center">
                    <template #default="{ scope }">
                        <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
                        <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="page"
                    :page-sizes="[5, 10, 15, 20]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"
            ></el-pagination>
        </el-card>

        <el-dialog :title="title" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
            <el-form :model="student" :rules="rules" ref="ruleForm">
                <el-form-item label="学生姓名" prop="sname" :label-width="formLabelWidth">
                    <el-input v-model="student.sname" autocomplete="off" />
                </el-form-item>
                <el-form-item label="学生性别" prop="sex" :label-width="formLabelWidth">
                    <el-radio v-model="student.sex" label="男">男</el-radio>
                    <el-radio v-model="student.sex" label="女">女</el-radio>
                </el-form-item>
                <el-form-item label="学生年龄" prop="age" :label-width="formLabelWidth">
                    <el-input v-model.number="student.age" autocomplete="off" />
                </el-form-item>
                <el-form-item label="家庭住址" prop="addr" :label-width="formLabelWidth">
                    <el-input v-model="student.addr" autocomplete="off" />
                </el-form-item>
                <el-form-item label="所在班级" prop="cid" :label-width="formLabelWidth">
                    <el-select v-model="student.cid" placeholder="请选择所在班级">
                        <el-option label="所有班级" value="0" />
                        <el-option :label="c.cname" :value="c.cid" v-for="c in classesList" :key="c.cid" />
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveStudent">保 存</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import studentApi from "@/api/student";
import classesApi from "@/api/classes";

export default {
    data() {
        // 自定义校验规则
        const checkAge = (rule, value, callback) => {
            if (!value) return callback(new Error("年龄不能为空"));
            if (!Number.isInteger(value)) return callback(new Error("年龄必须为数字"));
            if (value < 1 || value > 200) return callback(new Error("年龄在1-200之间"));
            callback();
        };

        return {
            studentList: [],
            page: 1,
            pageSize: 5,
            total: 100,
            studentSearch: {},
            classesList: [],
            dialogFormVisible: false,
            student: {},
            title: "添加学生",
            formLabelWidth: "100px",
            multipleSelection: [],
            sids: [],
            rules: {
                sname: [{ required: true, message: "请输入学生姓名", trigger: "blur" }],
                sex: [{ required: true, message: "请选择性别", trigger: "blur" }],
                age: [{ validator: checkAge, trigger: "blur" }],
                addr: [{ required: true, message: "请输入学生住址", trigger: "blur" }],
                cid: [{ required: true, message: "请选择学生班级", trigger: "blur" }]
            }
        };
    },
    created() {
        this.search();
        this.findAllClasses();
    },
    methods: {
        // 查询所有班级
        async findAllClasses() {
            const { data: res } = await classesApi.findAllClasses();
            if (res.code === 200) {
                this.classesList = res.data.list;
            }
        },
        // 条件查询带分页
        async search() {
            const { data: res } = await studentApi.search(this.page, this.pageSize, this.studentSearch);
            if (res.code === 200) {
                this.studentList = res.data.pr.rows;
                this.total = res.data.pr.total;
            }
        },
        // 添加学生
        addStudent() {
            this.title = "添加学生";
            this.student = {};
            this.dialogFormVisible = true;
        },
        // 保存学生
        async saveStudent() {
            this.$refs.ruleForm.validate(async (valid) => {
                if (valid) {
                    const url = this.student.sid ? "/student/update" : "/student/add";
                    const method = this.student.sid ? "put" : "post";
                    const { data: res } = await studentApi.save(url, method, this.student);
                    if (res.code === 200) {
                        this.$message.success(res.message);
                        this.dialogFormVisible = false;
                        this.search();
                    } else {
                        this.$message.error(res.message);
                    }
                }
            });
        },
        // 编辑学生
        handleEdit(row) {
            this.title = "修改学生";
            this.student = { ...row };
            this.dialogFormVisible = true;
        },
        // 选择变化
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        // 批量删除或单个删除
        async handleDelete(row) {
            this.sids = row ? [row.sid] : this.multipleSelection.map(m => m.sid);
            try {
                await this.$confirm(`是否删除学生ID: ${this.sids.join(", ")}?`);
                const { data: res } = await studentApi.deleteStudent(this.sids);
                if (res.code === 200) {
                    this.$message.success
